<template>
  <div class="basketball-pay-container">
    <div class="basketball-pay-header">
      <img class="left" @click="$router.go(-1)" src="../../../assets/imgs/icon-back@2x.png" alt>
      <div class="center">竞猜篮球投注</div>
    </div>
    <div class="select-back" @click="$router.go(-1)">+&nbsp;继续选择比赛</div>
    <div class="basketball-pay-content">
      <component
        :is="currentView[0]"
        @selectMatch="selectMatch"
        @selectBatchMatch="selectBatchMatch"
        @selectAllBatchMatch="selectAllBatchMatch"
        :selectedMatchs="selectedMatchs"
        :matchList="matchList"
      ></component>
    </div>
    <div class="basketball-pay-footer-advance">
      <div class="jcj">
        <div class="item" :key="i" v-for="(item, i) in getCNum()" @click="selectCC(item)">
          <div :class="{duihao: true, active: selectedCC[item]}">✔</div>
          <div class="text">{{item}}串1</div>
        </div>
      </div>
      <div class="ggfs">
        <div class="gg">过关方式（必选）</div>
        <div class="bs">投注倍数</div>
        <x-number v-model="bet_rate" :min="1"></x-number>
        <!-- <div class="yh" @click="showJJ"></div> -->
      </div>
      <selector placeholder="优惠券（请先确认投注备注）" v-model="user_coupon_id" :options="couponList"></selector>
      <!-- <div class="yhq">优惠券（请先确认投注备注）
        <x-icon type="ios-arrow-right" size="24"></x-icon>
      </div>-->
    </div>
    <div class="basketball-pay-footer">
      <div class="clear-btn" @click="goBuy(2)">发单</div>
      <div class="select-tip">
        <div>
          <div class="top">共{{matchNum()}}注{{money}}元</div>
          <div class="bottom">
            预计奖金
            <span>{{lowMoney}}-{{highMoney}}元</span>
          </div>
        </div>
      </div>
      <div class="go-buy" @click="goBuy(1)">付款</div>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import PaySelectMatch from "./PaySelectMatch";
import { XNumber, Selector } from "vux";
import cloneDeep from "lodash/cloneDeep";
import values from "lodash/values";
import keys from "lodash/keys";
import range from "lodash/range";
import { createMode } from "../../../util/func.js";
export default {
  components: {
    XNumber,
    Selector
  },
  data() {
    return {
      currentView: [PaySelectMatch],
      matchList: [],
      selectedMatchs: {},
      showJJModal: false,
      selectedCC: {},
      bet_rate: 1,
      couponList: [],
      user_coupon_id: "",
      money: 0,
      lowMoney: 0,
      highMoney: 0
    };
  },
  mounted() {
    const matchCacheObj = localStorage.getItem("payCache");
    if (matchCacheObj) {
      const {
        matchList,
        selectedMatchs,
        couponList,
        user_coupon_id,
        money,
        lowMoney,
        highMoney,
        tabIndex,
        selectedCC
      } = JSON.parse(matchCacheObj);
      this.matchList = matchList;
      this.selectedMatchs = selectedMatchs;
      this.couponList = couponList;
      this.user_coupon_id = user_coupon_id;
      this.money = money;
      this.lowMoney = lowMoney;
      this.highMoney = highMoney;
      this.tabIndex = tabIndex;
      this.selectedCC = selectedCC;
    } else {
      const { matchList = [], selectedMatchs = {}, tabIndex } =
        this.$route.params || {};
      this.matchList = matchList;
      this.selectedMatchs = selectedMatchs;
      this.tabIndex = tabIndex;
      this.getUseCouponList({ type: 1, page: 1, size: 100 }).then(res => {
        this.couponList = res.list.map(
          ({ user_coupon_id: key, title: value, expire_time }) => ({
            key,
            value: value + "-" + expire_time
          })
        );
      });
    }
  },
  beforeDestroy() {
    const matchCacheObj = JSON.parse(localStorage.getItem("matchCache"));
    matchCacheObj.selectedMatchs = cloneDeep(this.selectedMatchs);
    localStorage.setItem("matchCache", JSON.stringify(matchCacheObj));
  },
  methods: {
    ...mapActions({
      goBetLq: "match/goBetLq",
      getUseCouponList: "mine/getUseCouponList"
    }),
    // setLocalstorage () {
    //   const matchCacheObj = JSON.parse(localStorage.getItem('matchCache'));
    //   matchCacheObj.selectedMatchs = cloneDeep(this.selectedMatchs);
    //   localStorage.setItem('matchCache', JSON.stringify(matchCacheObj));
    // },
    selectMatch({ nm_matches_id, type, issue_num, i, value }) {
      if (!this.selectedMatchs[nm_matches_id]) {
        this.selectedMatchs[nm_matches_id] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num]) {
        this.selectedMatchs[nm_matches_id][issue_num] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num][type]) {
        this.selectedMatchs[nm_matches_id][issue_num][type] = {};
      }

      const typeObj = this.selectedMatchs[nm_matches_id][issue_num][type];
      if (typeObj[i]) {
        delete typeObj[i];
      } else {
        typeObj[i] = value;
      }
      this.selectedMatchs = cloneDeep(this.selectedMatchs);
    },
    selectBatchMatch({ nm_matches_id, type, issue_num, data }) {
      if (!this.selectedMatchs[nm_matches_id]) {
        this.selectedMatchs[nm_matches_id] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num]) {
        this.selectedMatchs[nm_matches_id][issue_num] = {};
      }
      this.selectedMatchs[nm_matches_id][issue_num][type] = data;
      this.selectedMatchs = cloneDeep(this.selectedMatchs);
    },
    selectAllBatchMatch({ nm_matches_id, issue_num, data }) {
      if (!this.selectedMatchs[nm_matches_id]) {
        this.selectedMatchs[nm_matches_id] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num]) {
        this.selectedMatchs[nm_matches_id][issue_num] = {};
      }
      this.selectedMatchs[nm_matches_id][issue_num] = data;
      this.selectedMatchs = cloneDeep(this.selectedMatchs);
      // this.setLocalstorage();
    },
    clearMatch() {
      this.selectedMatchs = {};
    },
    getCount() {
      return values(this.selectedMatchs)
        .map(s => values(s)[0])
        .filter(s => {
          return (
            keys(s.sf).length !== 0 ||
            keys(s.rf).length !== 0 ||
            keys(s.zs).length !== 0 ||
            keys(s.ks).length !== 0 ||
            keys(s.dxf).length !== 0
          );
        }).length;
      // return Object.keys(this.selectedMatchs).length;
    },
    goBuy(bet_type) {
      const count = this.getCount();
      if (count < 2) {
        this.$vux.toast.text("至少选择2场比赛");
        return;
      }
      const matches = keys(this.selectedMatchs)
        .map(s => {
          const issue_num_obj = this.selectedMatchs[s];
          const issue_num = keys(issue_num_obj)[0];
          const issue = issue_num_obj[issue_num];
          if (
            keys(issue.sf).length !== 0 ||
            keys(issue.rf).length !== 0 ||
            keys(issue.zs).length !== 0 ||
            keys(issue.ks).length !== 0 ||
            keys(issue.dxf).length !== 0
          ) {
            const scores = ["sf", "rf", "zs", "ks", "dxf"].reduce((t, c) => {
              t[c] = keys(issue[c] || {}).map(s => Number(s));
              return t;
            }, {});
            return {
              nm_matches_id: s,
              issue_num,
              ...scores
            };
          } else {
            return null;
          }
        })
        .filter(s => s);
      const mode = keys(this.selectedCC).join(",");
      if (!mode) {
        this.$vux.toast.text("过关方式必选");
        return;
      }
      localStorage.setItem(
        "payCache",
        JSON.stringify({
          matchList: this.matchList,
          selectedMatchs: this.selectedMatchs,
          couponList: this.couponList,
          tabIndex: this.tabIndex,
          user_coupon_id: this.user_coupon_id,
          money: this.money,
          lowMoney: this.lowMoney,
          highMoney: this.mohighMoneyney,
          selectedCC: this.selectedCC
        })
      );
      const body = {
        bet_type,
        bet_rate: this.bet_rate,
        mode,
        matches: JSON.stringify(matches),
        user_coupon_id: this.user_coupon_id,
        is_single: 0
      };
      if (bet_type === 2) {
        body.title = "竞彩篮球";
        body.money = this.money;
        body.desc = "";
        body.secrecy_level = 1;
        body.is_security_ratio = false;
        body.security_ratio = 1.3;
        body.is_allow_bill = true;
        // body.commission_rate = 11;
        this.$router.push({
          name: "BasketballBill",
          params: { matchParams: body }
        });
      } else {
        this.goBetLq(body).then(res => {
          if (res) {
            // this.matchList = res.date_list;
            this.$vux.toast.text("付款成功");
            this.$router.push({
              name: "PayConfirm"
            });
          }
        });
      }
    },
    startFilter() {
      this.showTip = false;
      this.showSelectModeModal = true;
    },
    onModalTabChange(key) {
      this.copyMode = key;
      this.allmatchmodes.forEach(s => {
        if (key === "0") {
          this.copymatchmode[s.key] = true;
        } else if (key === "1") {
          this.copymatchmode[s.key] = !this.copymatchmode[s.key];
        }
      });
      this.$forceUpdate();
    },
    onmatchmodeSelect(key) {
      const value = !!this.copymatchmode[key];
      this.copymatchmode[key] = !value;
      this.$forceUpdate();
    },
    showJJ() {
      this.showJJModal = !this.showJJModal;
    },
    getCNum() {
      const count = this.getCount();
      if (count < 2) {
        return [];
      } else {
        return range(2, (count > 8 ? 8 : count) + 1);
      }
    },
    selectCC(item) {
      if (this.selectedCC[item]) {
        this.$delete(this.selectedCC, item);
      } else {
        this.$set(this.selectedCC, item, true);
      }
    },
    matchNum() {
      const matches = keys(this.selectedMatchs)
        .map(s => {
          const issue_num_obj = this.selectedMatchs[s];
          const issue_num = keys(issue_num_obj)[0];
          const issue = issue_num_obj[issue_num];
          if (
            keys(issue.sf).length !== 0 ||
            keys(issue.rf).length !== 0 ||
            keys(issue.zs).length !== 0 ||
            keys(issue.ks).length !== 0 ||
            keys(issue.dxf).length !== 0
          ) {
            return [
              ...values(issue.sf),
              ...values(issue.rf),
              ...values(issue.zs),
              ...values(issue.ks),
              ...values(issue.dxf)
            ];
          } else {
            return null;
          }
        })
        .filter(s => s);
      const { zhushu, minjj, jj } = keys(this.selectedCC).reduce(
        (t, c) => {
          const modes = createMode(matches, Number(c), 1);
          t.jj += modes.reduce((mt, mc) => {
            const [a, b] = mc;
            const cjj = Number(a) * Number(b);
            if (cjj < t.minjj) {
              t.minjj = cjj;
            }
            mt += cjj;
            return mt;
          }, 0);
          t.zhushu += modes.length;
          return t;
        },
        { zhushu: 0, minjj: 10000000, jj: 0 }
      );

      const totalZhushu = this.bet_rate * zhushu;
      this.money = 2 * totalZhushu;
      this.lowMoney =
        this.bet_rate * 2 * (minjj === 10000000 ? 0 : minjj).toFixed(2);
      let highMoney = this.bet_rate * 2 * jj.toFixed(2);
      if (matches.length < 4 && highMoney > 200000) {
        highMoney = 200000.0;
      }
      if (matches.length < 6 && highMoney > 500000) {
        highMoney = 500000.0;
      }
      if (matches.length >= 6 && highMoney > 1000000) {
        highMoney = 1000000.0;
      }
      this.highMoney = highMoney;
      return totalZhushu;
    }
  }
};
</script>
<style lang="less">
.basketball-pay-container {
  .basketball-pay-header {
    position: relative;
    background: #d44743;
    height: 0.8rem;
    color: #ffffff;
    display: flex;
    justify-content: center;
    z-index: 10;
    .left {
      position: absolute;
      left: 0.2rem;
      width: 0.23rem;
      height: 0.4rem;
      top: 0.2rem;
    }
    .right {
      position: absolute;
      right: 0.2rem;
      top: 0.24rem;
      height: 0.29rem;
      width: 0.4rem;
    }
    .center {
      text-align: center;
      width: 3.2rem;
      line-height: 0.8rem;
      img {
        height: 0.16rem;
        width: 0.24rem;
      }
    }
  }
  .select-back {
    height: 0.6rem;
    line-height: 0.6rem;
    background: white;
    text-align: center;
    font-size: 0.26rem;
    color: #666666;
  }
  .basketball-pay-content {
    position: fixed;
    top: 1.52rem;
    bottom: 4.8rem;
    width: 100%;
    overflow-y: auto;
    z-index: 10;
  }
  .basketball-pay-footer-advance {
    position: fixed;
    bottom: 0.97rem;
    width: 100%;
    height: 3.8rem;
    background: white;
    .jcj {
      height: 1.6rem;
      padding: 0.2rem;
      .item {
        display: inline-block;
        border: 1px solid #d2d2d2;
        width: 1.2rem;
        height: 0.6rem;
        line-height: 0.6rem;
        margin-bottom: 0.2rem;
        margin-right: 0.2rem;
        .duihao {
          display: inline-block;
          background: #d2d2d2;
          color: white;
          height: 0.6rem;
          width: 0.3rem;
          text-align: center;
          &.active {
            background: #d44743;
          }
        }
        .text {
          display: inline-block;
          // width: 1rem;
          text-align: center;
        }
      }
    }
    .ggfs {
      display: flex;
      align-items: center;
      height: 0.96rem;
      border-top: 1px solid #eeeeee;
      .gg {
        width: 2rem;
        padding-left: 0.1rem;
        font-size: 0.22rem;
      }
      // .bs {
      //   width: 0.6rem;
      // }
      // .yh {
      //   width: 1.4rem;
      // }
    }
    .yhq {
      background: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0.2rem;
      border-top: 1px solid #eeeeee;
    }
  }
  .basketball-pay-footer {
    position: fixed;
    bottom: 0;
    height: 0.97rem;
    right: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    background: #ffffff;
    border-top: 1px solid #eeeeee;
    .clear-btn {
      border-right: 1px solid #eeeeee;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 1.4rem;
      color: #202020;
      font-size: 0.26rem;
      height: 0.97rem;
      justify-content: center;
      align-items: center;
    }
    .select-tip {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 3.5rem;
      color: #202020;
      font-size: 0.22rem;
      height: 0.97rem;
      text-align: center;
      .top {
        color: #d44743;
        margin-bottom: 0.08rem;
        text-align: center;
      }
      .bottom {
        span {
          color: #d44743;
        }
      }
    }
    .go-buy {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 2.6rem;
      background: #d44743;
      color: #ffffff;
      font-size: 0.34rem;
      height: 0.97rem;
    }
  }
  .select-type-modal {
    .modal-content {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      background: #ffffff;
      font-size: 0.24rem;
      color: #202020;
      div {
        width: 33%;
        display: inline-block;
        height: 0.6rem;
        line-height: 0.6rem;
      }
    }
  }
  .show-tip-modal {
    .modal-content {
      width: 2rem;
      position: fixed;
      top: 0.8rem;
      right: 0;
      background: #ffffff;
      font-size: 0.24rem;
      color: #202020;
      div {
        height: 0.6rem;
        line-height: 0.6rem;
        &.top {
          border-bottom: 1px solid #eeeeee;
        }
      }
    }
  }
  .modal-tab-wrapper {
    display: flex;
    margin-bottom: 0.2rem;
    // display: flex;
    justify-content: center;
    span {
      color: #747474;
      font-size: 0.26rem;
      width: 33.3%;
      padding: 0.12rem 0;
      border-top: 1px solid #d2d2d2;
      border-bottom: 1px solid #d2d2d2;
      border-left: 1px solid #d2d2d2;
      &.active-tab {
        background: #d44743;
        color: #fff;
      }
      &:nth-child(1) {
        border-top-left-radius: 0.1rem;
        border-bottom-left-radius: 0.1rem;
      }
      &:nth-child(2) {
        border-right: 1px solid #d2d2d2;
        border-top-right-radius: 0.1rem;
        border-bottom-right-radius: 0.1rem;
      }
    }
  }
  .modal-matchmode-wrapper {
    text-align: left;
    span {
      display: inline-block;
      text-align: center;
      color: #747474;
      font-size: 0.26rem;
      width: 30%;
      padding: 0.12rem 0;
      border: 1px solid #d2d2d2;
      margin-bottom: 0.1rem;
      border-radius: 0.1rem;
      &.active-matchmode {
        color: #d44743;
        border: 1px solid #d44743;
      }
      &:nth-child(3n + 2) {
        margin-left: 3%;
        margin-right: 3%;
      }
    }
  }
}
</style>
